﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ERPStore.Offers.Models;

namespace ERPStore.Offers.Repositories
{
	public class MockOfferRepository : IOffersRepository
	{
		public MockOfferRepository(ERPStore.Repositories.SqlRepository<Repositories.OffersDbContext> sqlRepository)
		{
			this.SqlRepository = sqlRepository;
			this.OfferList = new List<Models.OfferEx>();
			var defaultOffer = new Models.OfferEx()
			{
				Description = "Soldes Hiver 2012",
				EndDate = new DateTime(2012,2,14),
				StartDate = new DateTime(2012,1,11),
				Id = 1,
				Link = "soldes-hiver-2012",
				Name = "Soldes Hiver 2012",
				ProductSelectionId = 4,
				CSSTag = "soldeshiv2012",
				Title = "Les soldes d'hiver 2012",
				ProductList = new Lazy<IEnumerable<Models.OfferedProduct>>(() => 
					GetOfferedProductListBySelectionId(4)
					, true),
			};


			OfferList.Add(defaultOffer);
		}

		protected List<Models.OfferEx> OfferList { get; private set; }
		protected ERPStore.Repositories.SqlRepository<Repositories.OffersDbContext> SqlRepository { get; private set; }

		private IEnumerable<Models.OfferedProduct> GetOfferedProductListBySelectionId(int selectionId)
		{
			var list = SqlRepository.Query<Datas.OfferedProductData>(i => i.SelectionId == selectionId);
			var result = new List<Models.OfferedProduct>();
			foreach (var item in list)
			{
				result.Add(item.ToOfferedProductModel());
			}
			return result;
		}

		#region IOffersRepository Members

		public IQueryable<Models.OfferEx> GetOfferList()
		{
			return OfferList.AsQueryable();
		}

		public void Save(Models.OfferEx offer)
		{
			var existing = OfferList.SingleOrDefault(i => i.Id == offer.Id);
			if (existing == null)
			{
				existing = offer;
				offer.Id = OfferList.Max(i => i.Id) + 1;
				OfferList.Add(offer);
			}
			existing.CSSTag = offer.CSSTag;
			existing.Description = offer.Description;
			existing.EndDate = offer.EndDate;
			existing.Link = offer.Link;
			existing.Name = offer.Name;
			existing.ProductSelectionId = offer.ProductSelectionId;
			existing.StartDate = offer.StartDate;
			existing.Title = offer.Title;
			existing.ViewName = offer.ViewName;
		}

		#endregion
	}
}
